package com.shinji.tratu;

import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.widget.SearchView;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;

public class MainActivity extends SherlockFragmentActivity implements
		TabListener, SearchView.OnQueryTextListener,
		SearchView.OnSuggestionListener {
	String TAG = "MainActivity"; 
	ActionBar ab;
	View headerCustomView;
	ViewPager viewPager;
	HomePagerAdapter pagerAdapter;
	private SuggestionsAdapter mSuggestionsAdapter;
	private static final String[] COLUMNS = { BaseColumns._ID,
			SearchManager.SUGGEST_COLUMN_TEXT_1, };
	MatrixCursor suggestCursor;
	private WordDatabase wordDatabase;
	// Create the search view
	private SearchView searchView;
	private LookupAction lookupAction;
	private DatasetChanged dataSetChanged;
	Handler mHandler = new Handler();
	ArrayList<Word> listWords;
	private int mProgress = 100;
	Runnable mProgressRunner = new Runnable() {
		@Override
		public void run() {
			mProgress += 2;

			// Normalize our progress along the progress bar's scale
			int progress = (Window.PROGRESS_END - Window.PROGRESS_START) / 100
					* mProgress;
			Log.i(TAG, "progress = " + progress);
			setSupportProgress(progress);

			if (mProgress < 100) {
				mHandler.postDelayed(mProgressRunner, 50);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// getSherlock().setUiOptions(
		// ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);
		super.onCreate(savedInstanceState);
		// This has to be called before setContentView and you must use the
		// class in com.actionbarsherlock.view and NOT android.view
		// requestWindowFeature(Window.FEATURE_PROGRESS);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_main);
		viewPager = (ViewPager) findViewById(R.id.home_pager);
		pagerAdapter = new HomePagerAdapter(getSupportFragmentManager());
		viewPager.setAdapter(pagerAdapter);
		viewPager.setOffscreenPageLimit(1);
		setSupportProgressBarIndeterminateVisibility(false);
		ab = getSupportActionBar();
		ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		//
		ActionBar.Tab tab = ab.newTab();
		tab.setText(getString(R.string.dictionary));
		tab.setTabListener(this);
		ab.addTab(tab);
		//
		ActionBar.Tab tab2 = ab.newTab();
		tab2.setText(getString(R.string.recent));
		tab2.setTabListener(this);
		ab.addTab(tab2);
		//
		ab.setDisplayShowTitleEnabled(true);
		ab.setDisplayShowHomeEnabled(true);
		ab.setDisplayUseLogoEnabled(true);
		searchView = new SearchView(getSupportActionBar().getThemedContext());
		searchView.setQueryHint(getString(R.string.enter_word_to_search));
		searchView.setOnQueryTextListener(this);
		searchView.setOnSuggestionListener(this);
		if (mSuggestionsAdapter == null) {
			suggestCursor = new MatrixCursor(COLUMNS);
			mSuggestionsAdapter = new SuggestionsAdapter(getSupportActionBar()
					.getThemedContext(), suggestCursor);
		}

		searchView.setSuggestionsAdapter(mSuggestionsAdapter);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				ab.setSelectedNavigationItem(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		wordDatabase = WordDatabase.getInstance(getApplicationContext());
		listWords = wordDatabase.getAllRecords();

		// new GetAdIDAsync().execute();
		// Get tracker.
		
	}

	public void onResume() {
		super.onResume();
		if (dataSetChanged == null) {
			dataSetChanged = RecentFragment.getInstance();
		}
	}

	public void notifySearchDone() {
		if (dataSetChanged == null) {
			dataSetChanged = RecentFragment.getInstance();
		}
		if (dataSetChanged != null) {
			dataSetChanged.notifyDatasetChanged();
		}
	}

	public WordDatabase getWordDatabase() {
		return wordDatabase;
	}

	public ArrayList<Word> getListWords() {
		return listWords;
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Used to put dark icons on light action bar
		boolean isLight = true;// SampleList.THEME ==
								// R.style.Theme_Sherlock_Light;

		menu.add("Search")
				.setIcon(
						isLight ? R.drawable.ic_search_inverse
								: R.drawable.abs__ic_search)
				.setActionView(searchView)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
		getSupportMenuInflater().inflate(R.menu.main_menu, menu);
		// switch (viewPager.getCurrentItem()) {
		// case 0:
		// break;
		// case 1:
		// getSupportMenuInflater().inflate(R.menu.menu_recent, menu);
		// break;
		// default:
		// break;
		// }
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == R.id.clear_history) {
			Log.i(TAG, "clear history");
			clearHistory();
		} else if (item.getItemId() == R.id.rate) {
			rate();
		}else if(item.getItemId() == R.id.disable_ad){
			disableAd();
		}

		return false;
	}

	private void rate() {
		String url = "https://play.google.com/store/apps/details?id=com.shinji.tratu";
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(url));
		startActivity(i);
	}

	private void clearHistory() {
		DialogFragment newFragment = new FireMissilesDialogFragment();
		newFragment.show(getSupportFragmentManager(), TAG);
	}
	private void disableAd(){
		DisableAdFragment disableAdFragment = new DisableAdFragment();
		disableAdFragment.show(getSupportFragmentManager(), TAG);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		Util.hideSoftKeyboard(searchView, this);
		searchView.clearFocus();
		// Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG)
		// .show();
		query = query.trim();
		lookupAction.wantToLookup(query);
		return true;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		newText = newText.trim();
		if (newText == null || newText.length() == 0)
			return false;
		ArrayList<Word> tmpListWord = Util.searchInListWordsByKey(listWords,
				newText);
		suggestCursor = new MatrixCursor(COLUMNS);
		for (Word w : tmpListWord) {
			suggestCursor.addRow(new String[] { String.valueOf(w.getId()),
					w.getKey() });
		}
		mSuggestionsAdapter = new SuggestionsAdapter(getSupportActionBar()
				.getThemedContext(), suggestCursor);
		searchView.setSuggestionsAdapter(mSuggestionsAdapter);
		if (lookupAction != null) {
			lookupAction.onQueryTextChange(newText);
		}
		return false;
	}

	@Override
	public boolean onSuggestionSelect(int position) {
		return false;
	}

	@Override
	public boolean onSuggestionClick(int position) {
		Cursor c = (Cursor) mSuggestionsAdapter.getItem(position);
		String query = c.getString(c
				.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
		searchView.setQuery(query, false);
		// Toast.makeText(this, "Suggestion clicked: " + query,
		// Toast.LENGTH_LONG)
		// .show();
		return true;
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		int selectedIndex = ab.getSelectedNavigationIndex();
		viewPager.setCurrentItem(selectedIndex, true);
		if (selectedIndex == 0) {
			lookupAction = DicLookupFragment.getInstance();
		} else if (selectedIndex == 1) {
			lookupAction = RecentFragment.getInstance();
		} else {
			lookupAction = DicLookupFragment.getInstance();
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}

	public WordDatabase getDatabase() {
		return wordDatabase;
	}

	private class SuggestionsAdapter extends CursorAdapter {

		public SuggestionsAdapter(Context context, Cursor c) {
			super(context, c, 0);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(android.R.layout.simple_list_item_1,
					parent, false);
			return v;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView tv = (TextView) view;
			final int textIndex = cursor
					.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
			tv.setText(cursor.getString(textIndex));
		}
	}

	private class HomePagerAdapter extends FragmentStatePagerAdapter {

		public HomePagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int arg0) {
			if (arg0 == 0)
				return new DicLookupFragment();
			else
				return new RecentFragment();
		}

		@Override
		public int getCount() {
			return 2;
		}

	}

	private class GetAdIDAsync extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			getIdThread();
			return null;
		}

	}

	// Do not call this function from the main thread. erwise,
	// an IllegalStateException will be thrown.
	public void getIdThread() {

		Info adInfo = null;
		try {
			try {
				adInfo = AdvertisingIdClient
						.getAdvertisingIdInfo(getApplicationContext());
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (GooglePlayServicesRepairableException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (IOException e) {
			// Unrecoverable error connecting to Google Play services (e.g.,
			// the old version of the service doesn't support getting
			// AdvertisingId).

		} catch (GooglePlayServicesNotAvailableException e) {
			// Google Play services is not available entirely.
		}
		final String id = adInfo.getId();
		final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
		Log.i(TAG, "id = " + id);
	}

	public void showProgress() {
		// mProgress = 0;
		// mProgressRunner.run();
		setSupportProgressBarIndeterminateVisibility(true);

	}

	public void hideProgress() {
		// setSupportProgress(10000);
		setSupportProgressBarIndeterminateVisibility(false);
	}

	public LookupAction getLookupAction() {
		return lookupAction;
	}

	public void setLookupAction(LookupAction lookupAction) {
		this.lookupAction = lookupAction;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	public class FireMissilesDialogFragment extends DialogFragment {
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			// Add the buttons
			builder.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							RecentFragment.getInstance().onDeleteAll();
							wordDatabase.deleteAll();
						}
					});
			builder.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// User cancelled the dialog
						}
					});
			// Set other dialog properties
			builder.setMessage(R.string.clear_history_confirm).setTitle(
					R.string.clear_history);

			// Create the AlertDialog
			return builder.create();
		}
	}
	
	
	public class DisableAdFragment extends DialogFragment {
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);			
			builder.setNegativeButton(R.string.close,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// User cancelled the dialog
						}
					});
			// Set other dialog properties
			builder.setMessage(R.string.disable_ad_message).setTitle(
					R.string.disable_ad);

			// Create the AlertDialog
			return builder.create();
		}
	}
}
